package com.example.bookstore.service.Impl;

import com.example.bookstore.common.api.CommonResult;
import com.example.bookstore.mbg.mapper.BookMapper;
import com.example.bookstore.mbg.mapper.ChartMapper;
import com.example.bookstore.mbg.mapper.DealMapper;
import com.example.bookstore.mbg.mapper.UserMapper;
import com.example.bookstore.mbg.model.*;
import com.example.bookstore.service.RedisStringService;
import com.example.bookstore.service.UserService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: rain
 * @date: 2020/5/7 11:57
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private DealMapper dealMapper;

    @Autowired(required = false)
    private BookMapper bookMapper;

    @Autowired(required = false)
    private ChartMapper chartMapper;

    @Autowired
    private RedisStringService redisService;


    @Override
    public CommonResult register(String userid, String username,
                                 String password, String gender,
                                 String telephone, String email,
                                 String validCode) {
        if (getValidCode(email) == null) {
            return CommonResult.failed("该邮箱的验证码不存在");
        }
        if (!getValidCode(email).equals(validCode)) {
            return CommonResult.failed("邮箱验证码错误");
        }
        if (userMapper.selectByPrimaryKey(userid) != null) {
            return CommonResult.failed("该用户名已经存在");
        }

        User user = new User();
        user.setUserid(userid);
        user.setGender(gender);
        user.setPassword(password);
        user.setTelephone(telephone);
        user.setUsername(username);
        user.setEmail(email);
        userMapper.insert(user);
        LOGGER.info("doctor register request userid:{}", userid);
        return CommonResult.success("成功了bitch");
    }

    private String valid_register(String email) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        redisService.set(email, sb.toString());
        redisService.expire(email, 240);
        return sb.toString();
    }

    private String getDealid()
    {
        StringBuilder s=new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 12; i++) {
            s.append(random.nextInt(10));
        }
        return s.toString();
    }

    @Override
    public String getValidCode(String email) {
        return redisService.get(email);
    }

    @Override
    public String sendValidCode(String email) {
        String code = valid_register(email);
        return code;
    }

    @Override
    public CommonResult login(String userid, String password) {
        User p = userMapper.selectByPrimaryKey(userid);
        System.out.println(p.getPassword());
        if (p.getPassword().equals(password)) {
            System.out.println("成功了");
            return CommonResult.success("成功了bitch");
        } else {
            return CommonResult.failed("密码错误p");
        }
    }


    @Override
    public User getUserByUserId(String userid) {
        return userMapper.selectByPrimaryKey(userid);
    }

    @Override
    public Deal getDealRecord(String userid) {
        return dealMapper.selectByPrimaryKey(userid);
    }

    @Override
    public List<Book> getAllBooks(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return bookMapper.selectByExampleWithBLOBs(new BookExample());
    }

    @Override
    public List<Deal> getCommentByBook(int pageNum, int pageSize, String bookid) {
        DealExample b=new DealExample();
        b.createCriteria().andBookidEqualTo(bookid);
        PageHelper.startPage(pageNum, pageSize);
        return dealMapper.selectByExampleWithBLOBs(b);
    }

    @Override
    public List<Chart> getAllChart(int pageNum, int pageSize,String userid) {

        ChartExample c=new ChartExample();
        c.createCriteria().andUseridEqualTo(userid).andStatusEqualTo(0);
        PageHelper.startPage(pageNum, pageSize);
        return chartMapper.selectByExample(c);
    }

    @Override
    public CommonResult BuyBooksDirect(String bookid, String userid, int num,double price) {

        double money = num*price;
        Date date = new Date();
        Deal deal=new Deal();
        String text = "未评论";
        String dealid=getDealid();

        deal.setComment(text);
        deal.setBookid(bookid);
        deal.setDealtime(date);
        deal.setMoney(money);
        deal.setState(0);
        deal.setUserid(userid);
        deal.setDealid(dealid);

        dealMapper.insert(deal);

        return CommonResult.success("购买成功,待收货后评论");
    }





    @Override
    public CommonResult AddChart(String bookid, String userid){

        String chartid = getDealid();
        Chart chart = new Chart();
        chart.setChartid(chartid);
        chart.setBookid(bookid);
        chart.setUserid(userid);
        chart.setNum(1);
        chart.setStatus(0);

        chartMapper.insert(chart);

        return CommonResult.success("添加成功");
    }

    @Override
    public CommonResult AddNumInChart(int num,String userid,String bookid,String chartid) {
        ChartExample chartExample = new ChartExample();
        chartExample.createCriteria().andBookidEqualTo(bookid).andUseridEqualTo(userid);
        List<Chart> charts= chartMapper.selectByExample(chartExample);

        charts.get(0).setNum(num);
        chartMapper.updateByPrimaryKeySelective(charts.get(0));

        return CommonResult.success(bookid, "书籍在购物车中成功加一本");
    }

    @Override
    public CommonResult DeleteFromChart(String chartid, String userid) {
        Chart c = chartMapper.selectByPrimaryKey(chartid);
        if (c.getUserid().equals(userid)) {
            chartMapper.deleteByPrimaryKey(chartid);
            return CommonResult.success(c.getUserid(), "删除成功");
        }
        return CommonResult.failed("操作失败");
    }

    @Override
    public CommonResult AddComment(String dealid, String userid, String text) {
        Deal d = dealMapper.selectByPrimaryKey(dealid);
        if (d.getState() ==1) {
            return CommonResult.failed("已经评论了");
        }
        Date date = new Date();

        d.setComment(text);
        d.setDealtime(date);
        d.setState(1);

        dealMapper.updateByPrimaryKeySelective(d);
        return CommonResult.success(d.getDealid(), "添加评论成功");
    }

    @Override
    public List<Deal> ShowDealNeedComment() {
        DealExample dealExamples = new DealExample();
        dealExamples.createCriteria().andStateEqualTo(0);

        return dealMapper.selectByExample(dealExamples);
    }

    @Override
    public List<Deal> getDealByUsername(String userid) {
        DealExample dealExample = new DealExample();
        dealExample.createCriteria().andUseridEqualTo(userid);
        return dealMapper.selectByExampleWithBLOBs(dealExample);
    }

    @Override
    public CommonResult ModifyUserInformation(User user) {
        User u = userMapper.selectByPrimaryKey(user.getUserid());

        u.setUsername(user.getUsername());
        u.setEmail(user.getEmail());
        u.setPassword(user.getPassword());
        u.setGender(user.getGender());
        u.setTelephone(user.getTelephone());

        userMapper.updateByPrimaryKey(u);

        return CommonResult.success(user.getUserid(), "用户修改成功");
    }

    @Override
    public CommonResult getBookByBookname(String bname){
        BookExample bookExample = new BookExample();
        bookExample.createCriteria().andBnameEqualTo(bname);

        List<Book> books = bookMapper.selectByExample(bookExample);

        return CommonResult.success(books,"搜索成功");
    }
}